/**
 * Created by jijin on 2017/7/9.
 *
 * 文章列表组件
 */
import React, { Component } from 'react';
import {
  View,
  Text,
  TouchableHighlight,
  AsyncStorage,
  StyleSheet,
  Platform
} from 'react-native';
import GiftedListView from 'react-native-gifted-listview';
import {AppColors, AppSizes, AppFonts} from '@app/style';
import {Api} from '../../service';

import ArticleListItem from './article-list-item';
import AutoActivityIndicator from "../common/activity-indicator";

export default class ArticleList extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      firstLoader: true
    };
    //获取本地存储记录
    AsyncStorage.getItem('user_like_history')
      .then(historyLikes => {
        this.historyLikes = historyLikes ? JSON.parse(historyLikes) : [];
      }).catch(err => {
        alert(err);
      })
  }

  //
  renderRowView(article, sectionID, rowID) {
    let liked = false;
    if (this.historyLikes && this.historyLikes.length && this.historyLikes.includes(article.id)) {
      liked = true;
    }
    return (
      <ArticleListItem
        liked={liked}
        rowID={rowID}
        article={article}
        key={`sep:${sectionID}:${rowID}`}
        navigator={this.props.navigator}
      />
    )
  }

  //请求数据
  getArticles(page, callback, options) {
    //todo set state
    Api.getArticleList(page)
      .then(data => {
        this.setState({firstLoader: false});
        // alert(data.result.toString());
        const pagination = data.result.pagination;
        callback(data.result.data, {allLoaded: pagination.current_page >= pagination.total_page});
      })
      .catch(err => {
        alert(err);
      });
  }

  //翻页 - 在请求时的渲染
  renderPaginationFetchingView() {
    return (
      <View style={[customListStyles.paginationView, {backgroundColor: 'transparent'}]}>
        <AutoActivityIndicator size='small'/>
      </View>
    )
  }

  //翻页 - 正常的渲染
  renderPaginationWaitingView(paginateCallback) {
    return (
      <TouchableHighlight
        onPress={paginateCallback}
        underlayColor={AppColors.textMuted}
        style={customListStyles.paginationView}>
        <Text style={{fontSize: AppFonts.base.fontSize, color: AppColors.textDefault}}>
          加载更多
        </Text>
      </TouchableHighlight>
    )
  }

  //翻页 - 文章全部加载完时的渲染
  renderpaginationAllLoadedView() {
    return (
      <View
        style={[customListStyles.paginationView, {height: AppSizes.padding * 1.5, marginBottom: AppSizes.padding / 2, backgroundColor: AppColors.background}]}>
        <Text style={{fontSize: AppFonts.base.fontSize, color: AppColors.textMuted}}>
          到底啦~
        </Text>
      </View>
    )
  }

  render() {
    return (
      <View style={styles.listViewContainer}>
        <GiftedListView
          firstLoader={true}
          initialListSize={10}
          withSections={false}
          enableEmptySections={true}
          rowView={this.renderRowView.bind(this)}
          onFetch={this.getArticles.bind(this)}
          rowHashChanged={(r1, r2) => r1.id !== r2.id}
          // todo emptyView={}

          refreshable={true}
          refreshableTitile={'更新数据...'}
          refreshableTintColor={AppColors.brand.black}
          refreshableColors={[AppColors.brand.primary]}

          pagination={true}
          paginationFetchingView={this.renderPaginationFetchingView}
          paginationWaitingView={this.renderPaginationWaitingView}
          paginationAllLoadedView={this.renderpaginationAllLoadedView}
        />
        {
          this.state.firstLoader ?
            <View style={styles. ArticleListIndicator}>
              <AutoActivityIndicator/>
              {
                Platform.OS == 'ios' ? <Text style={styles.ArticleListIndicatorTitle}>数据加载中...</Text> : null
              }
            </View>

            : null

        }
      </View>
    )
  }
}

const styles = StyleSheet.create({
  listViewContainer: {
    position: 'relative',
    flex: 1,
    backgroundColor: AppColors.background
  },
  ArticleListIndicator: {
    position: 'absolute',
    left: 0,
    right: 0,
    top: 0,
    bottom: 0,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: AppColors.background
  },
  ArticleListIndicatorTitle: {
    textAlign: 'center',
    width: AppSizes.screen.width,
    marginTop: AppSizes.padding / 2,
    color: AppColors.textDefault
  }
});

const customListStyles = {
  //按钮的样式
  actionsLabel: {
    fontSize: AppFonts.h2.fontSize,
    color: AppColors.brand.primary
  },
  //翻页组件
  paginationView: {
    height: AppSizes.padding * 2,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: AppColors.cardBackground,
    marginLeft: AppSizes.padding / 2,
    marginRight: AppSizes.padding / 2,
    marginBottom: AppSizes.padding / 2,
  },
};

